import 'dart:developer';

import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:im_base/private/app_ext.dart';
import 'package:im_base/public/global/global.dart';
import 'package:im_base/public/service/tim_service.dart';
import 'package:permission_handler/permission_handler.dart';
import '../../../../../im_base.dart';
import 'package:im_base/public/ext/string_ext.dart';
import '../logic.dart';
import 'state.dart';

const String AUDIO_EDIT_ID = 'audioEditButton';
const String INPUT_AREA = 'inputArea';
const String EMOJI_EDIT = "emojiEdit";
const String SEND_MORE = 'sendMore';
const String EMOJI_WIDGET = 'emojiWidget';
const String KEYBOARD_PLACEHOLDER = "keyboardPlaceholder";
const String AUDIO_OVERLAY = "audioOverlay";

class InputLogic extends GetxController with WidgetsBindingObserver {
  final state = InputState();
  late ChatLogic chatLogic;

  @override
  void onReady() {
    chatLogic = Get.find<ChatLogic>(tag: state.id);
    state.chatId = chatLogic.state.id;
    state.isGroup = chatLogic.state.isGroup;
    super.onReady();
  }

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
      final height = MediaQuery.of(Get.context!).viewInsets.bottom;
      if (height > 0) {
        Global.KEYBOARD_HEIGHT = height;
        showInput();
        chatLogic.scrollBottom();
      } else {
        hideInput();
      }
    });
  }

  @override
  void onInit() {
    WidgetsBinding.instance!.addObserver(this);
    super.onInit();
  }

  @override
  void onClose() {
    WidgetsBinding.instance!.removeObserver(this);
    state.editingController.dispose();
    super.onClose();
  }

  ///切换语音输入,文字输入
  ///这里将emoji置为false
  toggleAudio() {
    state.isAudio = !state.isAudio;
    state.isEmoji = false;
    state.showMore=false;
    update([AUDIO_EDIT_ID, INPUT_AREA, EMOJI_EDIT,EMOJI_WIDGET]);
  }

  ///切换emoji 表情,文字输入
  ///无论是什么,这里都需要将语音置为false
  toggleEmoji() async {
    state.isEmoji = !state.isEmoji;
    state.isAudio = false;
    if (state.isEmoji) {
      hideSoftKeyboard();
    }
    update([EMOJI_EDIT, AUDIO_EDIT_ID, INPUT_AREA, EMOJI_WIDGET]);
  }

  ///点击聊天页面空白处,隐藏emoji表情
  hideEmoji() async {
    state.isEmoji = false;
    state.isAudio = false;
    update([EMOJI_EDIT, AUDIO_EDIT_ID, INPUT_AREA, EMOJI_WIDGET]);
  }

  ///接收输入内容,如果文字长度超过120,则进行更新操作
  ///以适配自动回行功能
  updateInputContent(String content) {
    state.inputContent = content;
    if (state.inputContent.length > 120) {
      update([INPUT_AREA]);
    }
    update([SEND_MORE]);
  }

  void addEmoji(String emoji) {
    state.inputContent += emoji;
    state.editingController.text = state.inputContent;
    update([SEND_MORE]);
  }

  ///用户按下语音输入,提示用户松开发送
  audioPressStart(double startPosition) async {
    state.startPosition = startPosition;
    state.audioNotify = "手指上滑,取消发送";
    showOverlay();
    state.audioHint = '松开发送';
    update([INPUT_AREA]);
    chatLogic.startRecord();
  }

  ///语音
  audioPressEnd() async {
    removeOverlay();
    state.audioHint = '按下说话';
    state.voiceIndicator = 'voice_volume_1.png';
    update([INPUT_AREA]);
    chatLogic.stopRecord();
    state.startPosition = 0;
  }

  ///发送语音时,手指移动距离,值计算Y轴距离
  ///移动距离超过80则认为是取消发送语音,
  ///更改提示消息及图片展示,同时通知 [ChatLogic]更新语音发送状态
  audioPressMove(double position) {
    state.cancelAudio = (position.abs() - state.startPosition.abs()) > 80;
    state.audioNotify = state.cancelAudio ? "松开手指,取消发送" : "手指上滑,取消发送";
    chatLogic.state.cancleAudio = state.cancelAudio;
    update([AUDIO_OVERLAY]);
  }

  ///发送消息,成功之后将该消息插入到消息列表中
  void sendMessage() {
    if (state.inputContent.isNullEmpty()) {
      showToast("发送消息不能为空");
      return;
    }
    TimService.instance.sendTextMessage(state.inputContent,
        id: state.chatId!,
        isGroup: state.isGroup ?? false, callBack: (callBack) {
      log("sendMessage--${callBack.code}---${callBack.data!.msgID}");
      if (callBack.code == 0) {
        resetInput();
        chatLogic.addNewMessage(callBack.data!);
      } else {
        showToast("消息发送失败:${callBack.desc}");
      }
    });
  }

  void sendTextMessage(String text) {
    if (text.isNullEmpty()) {
      showToast("发送消息不能为空");
      return;
    }
    TimService.instance.sendTextMessage(text,
        id: state.chatId ?? "",
        isGroup: state.isGroup ?? false, callBack: (callBack) {
      if (callBack.code == 0) {
        resetInput();
        chatLogic.addNewMessage(callBack.data!);
      } else {
        showToast("消息发送失败:${callBack.desc}");
      }
    });
  }

  ///消息发送成功之后,清空输入框内容
  void resetInput() {
    state.inputContent = '';
    state.editingController.clear();
    update([INPUT_AREA, SEND_MORE]);
  }

  ///展示更多,同时取消语音输入,取消emoji
  void showMore({bool? show}) {
    hideSoftKeyboard();
    state.showKeyBoard = false;
    state.showMore = show ?? true;
    state.isEmoji = false;
    state.isAudio = false;
    update([EMOJI_EDIT, INPUT_AREA, AUDIO_EDIT_ID, EMOJI_WIDGET]);
  }

  ///只要软键盘弹起,则展示输入UI
  void showInput() {
    state.showKeyBoard = true;
    state.showMore = false;
    state.isEmoji = false;
    state.isAudio = false;
    update([EMOJI_EDIT, INPUT_AREA, AUDIO_EDIT_ID, EMOJI_WIDGET]);
  }

  ///软键盘收起,去除占位的view
  void hideInput() {
    state.showKeyBoard = false;
    update([EMOJI_WIDGET]);
  }

  ///更新声音大小动画
  updateVoice(double voiceData) {
    if (voiceData > 0 && voiceData < 10) {
      state.voiceIndicator = "voice_volume_2.png";
    } else if (voiceData > 10 && voiceData < 30) {
      state.voiceIndicator = "voice_volume_3.png";
    } else if (voiceData > 30 && voiceData < 50) {
      state.voiceIndicator = "voice_volume_4.png";
    } else if (voiceData > 50 && voiceData < 70) {
      state.voiceIndicator = "voice_volume_5.png";
    } else if (voiceData > 70 && voiceData < 90) {
      state.voiceIndicator = "voice_volume_6.png";
    } else if (voiceData > 90 && voiceData < 100) {
      state.voiceIndicator = "voice_volume_7.png";
    } else if (voiceData > 100 && voiceData < 120) {
      state.voiceIndicator = "voice_volume_7.png";
    } else {
      state.voiceIndicator = "voice_volume_1.png";
    }
    update([AUDIO_OVERLAY]);
  }

  ///展示语音动画及手势提示信息
  showOverlay() {
    state.showAudioOverlay = true;
    update([AUDIO_OVERLAY]);
  }

  ///移除语音动画及手势信息
  removeOverlay() {
    state.showAudioOverlay = false;
    update([AUDIO_OVERLAY]);
  }

  void requestPermission() async{
    await Permission.microphone.request();
  }
}
